package zj.com.activities;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.xutils.DbManager;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import zj.com.adapter.DjcAdapter;
import zj.com.app.ZjApplication;
import zj.com.db.DBUtil;
import zj.com.model.DjcModel;
import zj.com.model.JcdInfoDB;
import zj.com.model.JcxDB;
import zj.com.model.JcxDetailDB;
import zj.com.model.UploadFile;
import zj.com.net.NetManager;
import zj.com.net.OnResponseListener;
import zj.com.util.DialogUtil;
import zj.com.util.LogUtils;
import zj.com.zj.R;

/**
 * Created by xi on 16/6/3.
 * 待检查
 */
public class DjcListActivity extends  BaseActivity implements View.OnClickListener{

    public TextView title_name;
    public ImageView left_iv;
    public TextView right_tv,cancel_tv,submit_tv,del_tv;
    public ImageView right_iv;
    public ListView listView;
    public TextView add_tc;
    public List<JcdInfoDB> list;
    public DjcAdapter adapter;
    public Intent intent;

    public LinearLayout edit_ll;
    public ProgressDialog dialog;

    public RelativeLayout error_rl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_djc_list);

        initView();
        initData();
    }
    public void initView(){

        error_rl = (RelativeLayout) findViewById(R.id.error_rl);
        cancel_tv = (TextView) findViewById(R.id.cancel_tv);
        cancel_tv.setOnClickListener(this);
        edit_ll = (LinearLayout) findViewById(R.id.edit_ll);
        submit_tv = (TextView) findViewById(R.id.submit_tv);
        submit_tv.setOnClickListener(this);

        del_tv =  (TextView) findViewById(R.id.del_tv);
        del_tv.setOnClickListener(this);

        left_iv = (ImageView) findViewById(R.id.left_iv);
        left_iv.setVisibility(View.VISIBLE);
        left_iv.setOnClickListener(this);
        title_name = (TextView) findViewById(R.id.title_name);
        right_tv = (TextView) findViewById(R.id.right_tv);
        right_tv.setVisibility(View.VISIBLE);
        right_tv.setText("编辑");
        right_tv.setOnClickListener(this);
        title_name.setText("待检查任务");

        right_iv = (ImageView) findViewById(R.id.right_iv);
        right_iv.setVisibility(View.VISIBLE);
        right_iv.setImageResource(R.drawable.edit_icon);
        right_iv.setOnClickListener(this);
        right_iv.setVisibility(View.GONE);

        listView = (ListView) findViewById(R.id.listView);
        add_tc = (TextView) findViewById(R.id.add_tc);
        add_tc.setOnClickListener(this);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                ZjApplication.isUpdateJcd = true;
                intent = new Intent(DjcListActivity.this, JcdEditActivity.class);
                JcdInfoDB  jcd =  list.get(position);
                ZjApplication.jcd = jcd;
                startActivity(intent);
            }
        });

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                add_tc.setVisibility(View.GONE);
                edit_ll.setVisibility(View.VISIBLE);
                right_tv.setVisibility(View.GONE);
                adapter.setIsEdit(true);
                adapter.setSelect(position);
                return false;
            }
        });
    }

    public void initData(){


        list =new ArrayList<JcdInfoDB>();
        adapter = new DjcAdapter(list,this);
        listView.setAdapter(adapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initDataFromDB();

    }

    public void initDataFromDB(){
        try {
            list =   DBUtil.getInstance(this).getDBManager().selector(JcdInfoDB.class).findAll();
            if(list !=null && list.size() > 0){
                adapter.setDataChange(list);
                error_rl.setVisibility(View.GONE);
                right_tv.setVisibility(View.VISIBLE);

            }else{
                list  = new ArrayList<>();
                adapter.setDataChange(list);
                right_tv.setVisibility(View.GONE);
                error_rl.setVisibility(View.VISIBLE);

            }

        } catch (DbException e) {
            e.printStackTrace();
            error_rl.setVisibility(View.VISIBLE);

        }
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.left_iv:
                finish();
                break;
            case R.id.right_iv:

                break;
            case R.id.add_tc:
               // uploadFile();

                ZjApplication.pgScan = null;
                ZjApplication.dqrJcdInfo = null;
                ZjApplication.jcd = null;
                ZjApplication.inspectItems.clear();
                ZjApplication.isUpdateJcd = false;
                intent = new Intent(this, JcdEditActivity.class);
                intent.putExtra("mode",1);
                startActivity(intent);
                break;
            case R.id.right_tv:
                add_tc.setVisibility(View.GONE);
                edit_ll.setVisibility(View.VISIBLE);
                right_tv.setVisibility(View.GONE);
                adapter.setIsEdit(true);
                break;
            case R.id.cancel_tv:
                add_tc.setVisibility(View.VISIBLE);
                edit_ll.setVisibility(View.GONE);
                right_tv.setVisibility(View.VISIBLE);
                adapter.setIsEdit(false);

                adapter.getSelectMap().clear();
                adapter.notifyDataSetChanged();
                adapter.setSelect(-1);
                break;
            case R.id.submit_tv:
                add_tc.setVisibility(View.VISIBLE);
                edit_ll.setVisibility(View.GONE);
                right_tv.setVisibility(View.VISIBLE);
                adapter.setIsEdit(false);
                selectMap =  adapter.getSelectMap();
                if(selectMap.size() == 0){
                    Toast.makeText(DjcListActivity.this, "请选择你要上传的数据", Toast.LENGTH_SHORT).show();
                    return;
                }
                upladJcdList =new ArrayList<>();
                for(Map.Entry<Integer, Boolean> entry:selectMap.entrySet()){

                    JcdInfoDB jcd =   list.get(entry.getKey());
                    upladJcdList.add(jcd);

                }



                dialog = DialogUtil.createProgressDialog(this, "提示", "上传图片中...");

                doSubmit();
                break;
            case R.id.del_tv:
                add_tc.setVisibility(View.VISIBLE);
                edit_ll.setVisibility(View.GONE);
                right_tv.setVisibility(View.VISIBLE);
                adapter.setIsEdit(false);

                delData();
                break;
        }

    }

    public List<JcdInfoDB> upladJcdList;

    //测试上传图片

    public void uploadFile(final int count,final JcdInfoDB jcd,JcxDetailDB jcdDetail){


        LogUtils.getInstance().error("uploadFile===="+jcd.getInspectionNo());
       final int c = 0;
        NetManager.getInstance(this).uploadFile(jcdDetail, new OnResponseListener<List<UploadFile>>() {
            @Override
            public void onComplete(boolean isOK, List<UploadFile> result, int errorCode, String errorMsg) {

                if(isOK){
                    int uploadCount = jcd.getCount();
                    uploadCount++;
                    jcd.setCount(uploadCount);
                    LogUtils.getInstance().error(uploadCount+"==========="+count);
                    if(uploadCount == count){
                        dialog.setMessage("上传数据中..");
                        uploadJcd(jcd);
                    }

                }else{
                    dialog.dismiss();

                }
            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {

                dialog.dismiss();
            }
        });

    }

    public int totalCount = 0;
    public Map<Integer,Boolean> selectMap;
    public int currentUpload = 0;


    Handler mHandler =new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0x2210:
                    doSubmit();
                    break;
            }
        }
    };

    //提交检查单
    public void doSubmit(){


        LogUtils.getInstance().error("======currentUpload======"+currentUpload+"=====listsize===="+upladJcdList.size());
        if(currentUpload +1 > upladJcdList.size()){

            dialog.dismiss();
            currentUpload = 0;
            Toast.makeText(DjcListActivity.this, "上传完毕", Toast.LENGTH_SHORT).show();
            return;
        }
        for(Map.Entry<Integer, Boolean> entry:selectMap.entrySet()){

            JcdInfoDB jcd =   list.get(entry.getKey());
            LogUtils.getInstance().error("===data==="+jcd.getInspectionNo());

        }

        JcdInfoDB jcd = upladJcdList.get(currentUpload);
        doData(jcd);


//        for(Map.Entry<Integer, Boolean> entry:selectMap.entrySet()){
//
//            JcdInfoDB jcd =   list.get(entry.getKey());
//            jcd.setSaveKey(entry.getKey());
//
//
//          }


    }


    public void doData(JcdInfoDB jcd){

        try{



        DbManager dbManager = DBUtil.getInstance(this).getDBManager();

        List<JcxDB> jcxList = dbManager.selector(JcxDB.class).where("inspectionno", "=", jcd.getInspectionNo()).findAll();
        int count = 0;
        if(jcxList == null || jcxList.size() == 0){

            dialog.dismiss();
            Toast.makeText(this,"检查单的检查项为空 请确定！",Toast.LENGTH_SHORT).show();
            return;
        }
        for(JcxDB jcx:jcxList){
            List<JcxDetailDB> detailList = dbManager.selector(JcxDetailDB.class).where("inspectionno", "=", jcx.getInspectionNo()).findAll();
            List<JcxDetailDB> uploadList = dbManager.selector(JcxDetailDB.class).where("inspectionno", "=", jcx.getInspectionNo()).and("points",">","0").and("imgs","!=","").and("riskname","!=","").and("content","!=","").findAll();
            LogUtils.getInstance().error(jcd.getInspectionNo()+"==========uploadList============"+uploadList.size());

            if(uploadList != null && uploadList.size() > 0){

                for(JcxDetailDB detail:uploadList){
                    uploadFile(uploadList.size(),jcd,detail);
                }
            }else{
                count++;
            }
            if(count ==jcxList.size() ){
                dialog.dismiss();
            }


        }

    }catch(Exception e){

        dialog.dismiss();

    }
    }

    //上传检查单
    public void uploadJcd(JcdInfoDB jcd){

        LogUtils.getInstance().error("uploadData===="+jcd.getInspectionNo());

        NetManager.getInstance(this).doAddInspection(jcd, new OnResponseListener<JcdInfoDB>() {
            @Override
            public void onComplete(boolean isOK, JcdInfoDB result, int errorCode, String errorMsg) {

                if(isOK){
                    currentUpload++;
                    delJcdInfoById(result);
                   // selectMap.remove(result.getSaveKey());
                    LogUtils.getInstance().error("========remove=========="+result.getInspectionNo());
//                    if(totalUploadCount == totalCount){
//                        Toast.makeText(DjcListActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
//                        dialog.dismiss();
//
//                    }

                    mHandler.sendEmptyMessage(0x2210);


                }else{

                    Toast.makeText(DjcListActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();

                }

            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {
                Toast.makeText(DjcListActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });
    }


    public void delData(){

        try{
            Map<Integer,Boolean> selectMap =  adapter.getSelectMap();
            for(Map.Entry<Integer, Boolean> entry:selectMap.entrySet()){

                JcdInfoDB jcd =   list.get(entry.getKey());

                delJcdInfoById(jcd);
            }
            initDataFromDB();
        }catch(Exception e){
            LogUtils.getInstance().error("delData====="+e.toString());

        }

    }

    public  void delJcdInfoById(JcdInfoDB jcd){

        try{
            DBUtil.getInstance(this).getDBManager().delete(jcd);
            List<JcxDB> list = DBUtil.getInstance(this).getDBManager().selector(JcxDB.class).where("inspectionno","=",jcd.getInspectionNo()).findAll();
            if(list != null){
                for(JcxDB jcx:list){
                    DBUtil.getInstance(this).getDBManager().delete(JcxDetailDB.class, WhereBuilder.b("inspectionno", "=", jcx.getInspectionNo()));

                }
            }
            DBUtil.getInstance(this).getDBManager().delete(JcxDB.class, WhereBuilder.b("inspectionno", "=", jcd.getInspectionNo()));

            initDataFromDB();
        }catch (Exception e){

            LogUtils.getInstance().error("delJcdInfoById====="+e.toString());
        }

    }
}
